package tree.迭代bfs;

import tree.Node;

import java.util.*;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName IM多叉树的后序遍历590.java
 * @Description https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/
 * @createTime 2021年06月18日 19:06:00
 */
public class IM多叉树的后序遍历590 {
    /*
    //递归方案
    List<Integer> list=new ArrayList<>();

    public List<Integer> postorder(Node root) {
        if (root == null) {
            return list;
        }
        recurse(root);
        return list;
    }

    private void recurse(Node node) {
        if (node == null) {
            return;
        }
        for (Node child : node.children) {
            recurse(child);
        }
        list.add(node.val);
    }*/

    public List<Integer> postorder(Node root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Deque<Node> deque = new LinkedList<>();
        deque.offer(root);
        while (!deque.isEmpty()) {
            //todo 这里取第一个
            Node node = deque.pollFirst();
            list.add(node.val);
            List<Node> children = node.children;
            //Collections.reverse(children);
            for (Node child : children) {
                //todo 放到第一个
                deque.offerFirst(child);
            }
        }
        //todo 翻转
        Collections.reverse(list);
        return list;
    }

}

